#! /bin/sh

erl -pa ../src -name ec2nodefinder_checkah -eval '
  Host = lists:last (string:tokens (atom_to_list (node ()), "@")),
  [ "com", "amazonaws" | Rest ] = lists:reverse (string:tokens (Host, "."))
' -noshell -noinput -s erlang halt >/dev/null 2>&1

if test $? = 0
  then
    echo "info: EC2 detected" 1>&2

    which ec2-describe-instances >/dev/null 2>/dev/null

    test $? = 0 || {
      echo "ERROR: ec2-describe-instances not installed (http://developer.amazonwebservices.com/connect/entry.jspa?externalID=351)" 1>&2
      exit 77
    }

    which java >/dev/null 2>/dev/null

    test $? = 0 || {
      echo "ERROR: java not installed" 1>&2
      exit 77
    }
  else
    echo "info: EC2 not detected" 1>&2
  fi

cleanup () {
  trap - EXIT 

  erl -pa ../src -name combonodefinder_killah -eval '
    Host = lists:last (string:tokens (atom_to_list (node ()), "@")),
    Other = list_to_atom ("combonodefinder_test1@" ++ Host),
    rpc:call (Other, erlang, halt, [])
  ' -noshell -noinput -s erlang halt
}

trap cleanup INT QUIT TERM EXIT
set -e

erl -pa ../src -name combonodefinder_test1 -eval '
  { ok, [ App ] } = file:consult ("../src/combonodefinder.app"),
  ok = application:load (App),
  ok = combonodefinder:start (),
  receive after 100000 -> ok end
' -noshell -noinput -s erlang halt &

erl -pa ../src -name combonodefinder_test2 -eval '
  [] = erlang:nodes (),
  { ok, [ App ] } = file:consult ("../src/combonodefinder.app"),
  ok = application:load (App),
  ok = combonodefinder:start (),
  ok = combonodefinder:discover (),
  timer:sleep (1000),
  Host = lists:last (string:tokens (atom_to_list (node ()), "@")),
  Other = list_to_atom ("combonodefinder_test1@" ++ Host),
  true = lists:member (Other, erlang:nodes ())
' -noshell -noinput -s erlang halt 

exit 0
